<?php
/**
 * Copyright (c) 2018-2019.
 *  This file is part of the moonpie production
 *  (c) johnzhang <875010341@qq.com>
 *  This source file is subject to the MIT license that is bundled
 *  with this source code in the file LICENSE.
 */

/**
 * Created by PhpStorm.
 * User: johnzhang
 * Date: 2019/7/31 0031
 * Time: 上午 9:34
 */

namespace moonpie\plugin\wechat_account\traits;


use app\common\service\App;
use moonpie\plugin\wechat_account\model\WechatAccount;
use think\Hook;

trait ControllerTrait
{
    /** @var \think\Request $request*/
    protected $request;
    protected function currentWechatAccount()
    {
        $account = null;
        if($this->request->has('app_id')){
            $account = WechatAccount::loadByAppid($this->request->param('app_id'));
        }else if($this->request->has('account_id')){
            $account = WechatAccount::loadById($this->request->param('account_id'));
        }
        if(!$account) {
            $this->error('没有指定的公众号信息');
        }
        $this->request->bind('current_wechat_account', $account);
    }
    protected function wechatAccountServe()
    {
        /** @var \moonpie\plugin\wechat_account\model\WechatAccount $account */
        $account = $this->request->current_wechat_account;
        $server = $account->getService()->server;
        try {
            $params = compact('account', 'server');
            Hook::listen('init_wechat_account_handlers', $params);
            $server->serve()->send();
        } catch (\Exception $e) {
            if (App::$debug) throw $e;
        }
    }
}